package com.mediacloud.app.newsmodule.fragment.navlive

import android.os.Bundle
import android.os.Handler
import android.os.Looper
import android.os.Message
import android.text.TextUtils
import android.util.Log
import android.view.View
import android.view.ViewGroup
import android.widget.Toast
import androidx.core.content.ContextCompat
import androidx.lifecycle.LifecycleOwner
import androidx.recyclerview.widget.LinearLayoutManager
import com.blankj.utilcode.util.NetworkUtils
import com.mediacloud.app.assembly.util.AppUtils
import com.mediacloud.app.assembly.util.DateParse
import com.mediacloud.app.cloud.ijkplayersdk.auth.URLAuth
import com.mediacloud.app.cloud.ijkplayersdk.obj.MediaMusicItem
import com.mediacloud.app.controller.live.IProgram
import com.mediacloud.app.controller.live.ProgramMod
import com.mediacloud.app.fbnavsk.navPaddingTopMatch
import com.mediacloud.app.model.activity.FragmentActivityBase
import com.mediacloud.app.model.news.ArticleItem
import com.mediacloud.app.model.news.ArticleItemReciver
import com.mediacloud.app.model.news.CatalogItem
import com.mediacloud.app.model.news.ProgramListItem
import com.mediacloud.app.model.news.kt.TypeX
import com.mediacloud.app.model.utils.ViewUtils
import com.mediacloud.app.model.view.floatwin.FloatButtonGroup
import com.mediacloud.app.nav2.fragment.HqyNavFragment
import com.mediacloud.app.newsmodule.R
import com.mediacloud.app.newsmodule.activity.microlive.BaseRecyclerAdapter
import com.mediacloud.app.newsmodule.service.AudioItem
import com.mediacloud.app.newsmodule.utils.KillMusicUtils
import com.mediacloud.app.newsmodule.utils.LiveMediaPlayBackInvoker
import com.mediacloud.app.newsmodule.utils.VideoAddressGet
import com.mediacloud.app.newsmodule.utils.share.ShareWrap
import com.mediacloud.app.reslib.enums.AppFactoryGlobalConfig
import com.mediacloud.app.reslib.enums.XKey
import com.mediacloud.app.reslib.util.DataInvokeUtil
import com.tencent.mmkv.MMKV
import com.utils.DeviceUtils
import com.yoake.media.player.XPlayer
import com.yoake.media.player.controller.component.PrepareView
import com.yoake.media.player.utils.XVideoBitRate
import com.yoake.media.player.utils.XVideoItem
import com.yoake.media.player.utils.interfaces.OnReturnBackClickListener
import io.reactivex.Observable
import io.reactivex.Observer
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.disposables.Disposable
import io.reactivex.schedulers.Schedulers
import kotlinx.android.synthetic.main.navigate_livecontent.videoPlayerContainer
import kotlinx.android.synthetic.main.navigate_livefragment.*
import org.greenrobot.eventbus.EventBus
import org.jetbrains.anko.collections.forEachWithIndex
import org.json.JSONArray
import org.json.JSONException
import org.json.JSONObject
import xyz.doikki.videoplayer.player.BaseVideoView
import xyz.doikki.videoplayer.player.VideoView
import java.text.SimpleDateFormat
import java.util.*
import java.util.concurrent.TimeUnit

/**
 * 单页面直播视频
 *
 * 直播导航  带播放器的
 */
class NavigateLiveFragment : HqyNavFragment()/*, OnLookBackTimeStampChangedListener */ {
    private var audioPlayer: AudioLiveView? = null
    private var videoPlayer: XPlayer? = null
    private var beforeIsPlay = false

    private var dateAdapter: NavLiveProgramDateAdapter? = null
    private var channelTableAdapter: NavLiveChannelTableAdapter? = null
    private var navLiveDropDownListAdapter: NavLiveDropDownListAdapter? = null

    private var pageIndex = 1

    private var perPageSize = 200
    private var programFragment: NavigateLiveProgramFragment? = null
    private var catalog: CatalogItem? = null

    private var lineMap: MutableMap<String, String> = LinkedHashMap()

    //  private var videoPlayObj = VideoPlayObj()
    //直播中的资源
    private var playVideoItem: XVideoItem? = null
    private var isAutoPlay = false
    //  private var navLiveShare: View? = null

    private var dropDownChannelView: View? = null
    private var closeChannelList: View? = null
    private var moreChannelLayout: View? = null
    var shareWrap: ShareWrap? = null
    override fun getLayoutResID(): Int {
        return R.layout.navigate_livefragment
    }

    override fun initView() {
//        loadingView = findViewById(R.id.mLoadingView)
        loadingView = findViewById(R.id.mLoadingView);
        videoPlayer = findViewById(R.id.videoPlayer)
        videoPlayer?.onResumePlay = false
        videoPlayer?.playWithMute = true
        videoPlayer?.prepareView?.fadeOutAnimMoment = PrepareView.FADE_OUT_ANIM_WHEN_PLAYING
        initStateView()
        shareWrap = ShareWrap(requireContext(), false)
        shareWrap?.setShowFunctionNoCollection(true);
        showStateView(TYPE_LOADING, false)
//        showStateView(TYPE_LOADING, false)

        retryTips?.setOnClickListener {
            if (currentState != TYPE_LOADING) {
                if (NetworkUtils.isConnected()) {
                    showStateView(TYPE_LOADING, false)
                    getDate()
                }
            }
        }

    }


    override fun initOther() {
        super.initOther()
        catalog = fragmentArguments.getParcelable("catalog")
        getDate()

    }

    private fun getLookBack(url: String, cdnCode: String?, startTime: Long, endTime: Long) {

        val params: MutableMap<String, Any> = HashMap()
        params["url"] = url
        if (!TextUtils.isEmpty(cdnCode)) {
            params["cdn_code"] = "$cdnCode"
        }
        params["start_time"] = startTime
        if (endTime != 0L) {
            params["end_time"] = endTime
        }
        DataInvokeUtil.ziMeiTiApi.getLookBack(params)
            .subscribeOn(Schedulers.io())
            .observeOn(AndroidSchedulers.mainThread())
            .subscribe(object : Observer<JSONObject> {
                override fun onSubscribe(d: Disposable) {
                }

                override fun onNext(t: JSONObject) {
                    if (activity == null || requireActivity().isFinishing || requireActivity().isDestroyed || isDispose) {
                        return
                    }
                    if (t.optBoolean("state")) {
                        val dataObject = t.optJSONObject("data")
                        if (dataObject?.optString(LiveMediaPlayBackInvoker.Url)?.isEmpty() == false) {
                            val xVideoItem = XVideoItem()
                            val url = dataObject.optString(LiveMediaPlayBackInvoker.Url)
                            xVideoItem.cdnIv = AppFactoryGlobalConfig.ServerAppConfigInfo.OtherConfig.vms_cdn_iv
                            xVideoItem.cdnKey = AppFactoryGlobalConfig.ServerAppConfigInfo.OtherConfig.vms_cdn_key
                            val xVideoBitRate = XVideoBitRate(getString(R.string.standard_quility), url, cdnEncrypt)
                            xVideoItem.bitRates.add(xVideoBitRate)
                            videoPlayer?.addVideoItem(xVideoItem)
                            if(DeviceUtils.isCus(requireContext())){
                                videoPlayer?.setDolbySwitchViewState(true, null)
                            }
                            videoPlayer?.bottomControl?.setPlayingBack(true)
                            audioPlayer?.let {
                                val items = ArrayList<MediaMusicItem>(1)
                                val audioItem = AudioItem()
                                audioItem.url = url
                                audioItem.cdnEncrypt = cdnEncrypt
                                audioItem.cdnIv = AppFactoryGlobalConfig.ServerAppConfigInfo.OtherConfig.vms_cdn_iv
                                audioItem.cdnKey = AppFactoryGlobalConfig.ServerAppConfigInfo.OtherConfig.vms_cdn_key
                                items.add(audioItem)
                                it.setData(items)
                            }
                        } else {
                            ViewUtils.showSnackBar(mRootView, R.string.getplaybackurlerror)
                        }
                    }
                }

                override fun onError(e: Throwable) {
                    if (activity == null || requireActivity().isFinishing || requireActivity().isDestroyed || isDispose) {
                        return
                    }
                    ViewUtils.showSnackBar(mRootView, R.string.getplaybackurlerror)
                }

                override fun onComplete() {
                }
            })
    }

    private var intervalDisposable: Disposable? = null
    private var playBillDisposable: Disposable? = null

    //获取日期相关数据
    private fun getDate() {
        val params: MutableMap<String, String> = HashMap()
        params["no_content"] = "1"
        params["client"] = DataInvokeUtil.ClientFlag
        params["page"] = "$pageIndex"
        params["perPage"] = "$perPageSize"
        DataInvokeUtil.ziMeiTiApi.getContentList("${catalog?.catid}", params)
            .map {
                val sdf = SimpleDateFormat("yyyyMMdd", Locale.CHINA)
                val sdf2 = SimpleDateFormat("MM/dd", Locale.CHINA)
                val data = NavLiveData()
                data.readFromJson(it.body())
                if (data.state) {
                    data.weekList?.forEach {
                        it.date_format = sdf2.format(sdf.parse(it.date))
                    }
                }
                data
            }
            .onErrorReturn { null }
            .subscribeOn(Schedulers.io())
            .observeOn(AndroidSchedulers.mainThread())
            .subscribe(object : Observer<NavLiveData> {
                override fun onSubscribe(d: Disposable) {

                }

                override fun onNext(data: NavLiveData) {
                    if (activity == null || requireActivity().isFinishing || requireActivity().isDestroyed || isDispose) {
                        return
                    }

                    //必须 的
                    val floatData = data.orginData?.optJSONObject("data")
                    if (pageIndex == 1) {
                        if (FloatButtonGroup.haveFloatField(floatData)) {
                            initFloatWin(floatData)
                        } else {
                            hideFloatWin()
                        }
                    }

                    initappfacContent()
                 //   updateDateList()
                  //  updateTableChannel()
                    if (data.articleList!!.size > 0) {
                        channelTableAdapter!!.data.clear()
                        channelTableAdapter!!.data.addAll(data.articleList)

                        updateTableChannel()

                        navLiveDropDownListAdapter!!.data.clear()
                        navLiveDropDownListAdapter!!.data.addAll(channelTableAdapter!!.data)
                        navLiveDropDownListAdapter!!.selectedIndex = channelTableAdapter!!.selectedIndex
                        mRecyclerView3.adapter = navLiveDropDownListAdapter
                        mRecyclerView3.scrollToPosition(channelTableAdapter!!.selectedIndex)
                    }
                    if (data.weekList?.isEmpty() == false) {
                        dateAdapter!!.data.addAll(data.weekList!!)
                        updateDateList()
                    }
                    if (data.weekList?.isEmpty() == false && data.articleList?.isEmpty() == false) {
                        val videoId: String? = data.articleList[0].vid
                        val date = data.weekList!![dateAdapter!!.selectedIndex].date
                        if (date?.isEmpty() == false) {
                            if (channelTableAdapter!!.getItem(0) != null)
                                addProgramListFragment(
                                    videoId + "",
                                    date,
                                    "${channelTableAdapter!!.getItem(0).id}",
                                    channelTableAdapter!!.getItem(0).title,
                                    data.articleList[0]
                                )

                        }
                    }
                    //


                    data.navigate?.let {
                        it["style_other"]?.let {
                            val style = it as HashMap<String, String>
                            radioImageUrl = style["radio_bitmap"]
                            audioPlayer?.setBackgroundImageUrl(radioImageUrl)
                        }
                    }
                    getPlayBill(data.articleList)
                    closeStateView()
                }

                override fun onError(e: Throwable) {
                    if (activity == null || requireActivity().isFinishing || requireActivity().isDestroyed || isDispose) {
                        return
                    }

                    showStateView(TYPE_NET_NOT_GIVE_FORCE, false)
                }

                override fun onComplete() {
                }
            })
        intervalDisposable = Observable.interval(30, TimeUnit.SECONDS)
            .observeOn(AndroidSchedulers.mainThread())
            .subscribe {
            navLiveDropDownListAdapter?.notifyDataSetChanged()
        }
    }

    /**
     * 获取当天所有栏目的节目列表
     */
    private fun getPlayBill(items: MutableList<ArticleItem>) {
        Observable.create<String> {
            val map: MutableMap<String, Int> = HashMap()
            items.forEach { item ->
                if (!TextUtils.isEmpty(item.vid)) {
                    map[item.vid] = 1
                    if (!TextUtils.isEmpty(item.video)) {
                        try {
                            val video = JSONObject(item.video)
                            map[item.vid] = video.optInt("liveSourceType", 1)
                        } catch (e: JSONException) {
                            e.printStackTrace()
                        }
                    }
                }
            }
            val jsonArray = JSONArray()
            map.forEach {
                val jsonObject =JSONObject()
                jsonObject.put("vid", it.key)
                jsonObject.put("live_source_type", it.value)
                jsonArray.put(jsonObject)
            }
            it.onNext(jsonArray.toString())
        }.flatMap {
            DataInvokeUtil.ziMeiTiApi
                .getPlayBillMultiple(it)
        }
            .map {
                val sdf2 = SimpleDateFormat("HH:mm", Locale.CHINA)
                val result = it.body()
                val channelPlayBills: MutableMap<String, MutableList<XPlayBill>?> = HashMap()
                if (result!!.optBoolean("state")) {
                    result!!.optJSONObject("data")?.optJSONArray("meta")?.let { metaArray ->
                        val size = metaArray.length()
                        for (i in 0 until size) {
                            metaArray.optJSONObject(i)?.let { metaObject ->
                                val playBills: MutableList<XPlayBill> = ArrayList()

                                metaObject.optJSONArray("playbill")?.let { outsidePlayBill ->
                                    if (outsidePlayBill.length() > 0) {

                                        outsidePlayBill.optJSONObject(0).optJSONArray("playbill")?.let { billArray ->
                                            val size2 = billArray.length()
                                            for (k in 0 until size2) {
                                                val playBill = XPlayBill()
                                                val billObject = billArray.optJSONObject(k)
                                                playBill.Name = billObject.optString("Name")
                                                playBill.starttime = billObject.optString("starttime")
                                                playBill.endtime = billObject.optString("endtime")
                                                playBill.startStamp = billObject.optLong("starttimestamp") * 1000
                                                playBill.endStamp = billObject.optLong("endtimestamp") * 1000
                                                playBill.start_format = sdf2.format(playBill.startStamp)
                                                playBill.end_format = sdf2.format(playBill.endStamp)
                                                playBills.add(playBill)
                                            }
                                        }

                                    }
                                }
                                channelPlayBills[metaObject.optString("vid")] = playBills
                            }
                        }
                    }
                }
                channelPlayBills
            }
            .onErrorReturn { null }
            .subscribeOn(Schedulers.io())
            .observeOn(AndroidSchedulers.mainThread())
            .subscribe(object : Observer<MutableMap<String, MutableList<XPlayBill>?>> {
                override fun onSubscribe(d: Disposable) {
                    playBillDisposable = d
                }

                override fun onNext(t: MutableMap<String, MutableList<XPlayBill>?>) {
                    navLiveDropDownListAdapter?.channelPlayBills?.clear()
                    navLiveDropDownListAdapter?.channelPlayBills?.putAll(t)
                    navLiveDropDownListAdapter?.notifyDataSetChanged()
                }

                override fun onError(e: Throwable) {

                }

                override fun onComplete() {

                }
            })
    }

    private fun initappfacContent() {
        dropDownChannelView = findViewById(R.id.dropDownChannelView)
        closeChannelList = findViewById(R.id.closeChannelList)

        moreChannelLayout = findViewById(R.id.moreChannelLayout)
        navLiveDropDownListAdapter = NavLiveDropDownListAdapter(requireActivity())
        moreChannelLayout?.setOnClickListener {
            dropDownChannelView?.visibility = View.VISIBLE
            navLiveDropDownListAdapter!!.data.clear()
            navLiveDropDownListAdapter!!.data.addAll(channelTableAdapter!!.data)
            navLiveDropDownListAdapter!!.selectedIndex = channelTableAdapter!!.selectedIndex
            mRecyclerView3.adapter = navLiveDropDownListAdapter
            mRecyclerView3.scrollToPosition(channelTableAdapter!!.selectedIndex)

        }
        val closeListener = { _: View? ->
            dropDownChannelView?.visibility = View.GONE
            navLiveDropDownListAdapter!!.data.clear()
            mRecyclerView3.adapter = null
        }
        closeChannelList?.setOnClickListener(closeListener)
        mRecyclerView3.layoutManager = LinearLayoutManager(requireContext())

        videoPlayer?.prepareView?.fadeOutAnimMoment = PrepareView.FADE_OUT_ANIM_WHEN_PLAYING
        videoPlayer?.bottomControl?.setOnReturnBackClickListener(object : OnReturnBackClickListener {
            override fun onReturnBackClicked() {

                var item: ProgramListItem? = null
                programList?.let {
                    for (i in it.indices) {
                        if (ProgramListItem.getItemState(it[i]) == ProgramListItem.GuideItemState.LIVE) {
                            item = it[i]
                            break
                        }
                    }
                }
                item?.let {

                    handleReplay(it)
                }
                item?.startLong?.let {
                    setPlayingStartTime(it)
                }
            }
        })
      //  videoPlayer?.setWindowNoTitle()
        videoPlayer?.hideTitleBackViewWhenInNormalState()
        isAutoPlay = MMKV.defaultMMKV().decodeBool(XKey.AUTO_PLAY, false);
        videoPlayer?.autoPlay = isAutoPlay
        videoPlayer?.setOnTitleMoreClickListener {
            shareWrap?.init(mCurrentLiveArticleItem, CatalogItem())
            shareWrap?.show(mRootView)
        }
        mRecyclerView1.layoutManager = LinearLayoutManager(requireContext(), LinearLayoutManager.HORIZONTAL, false)
        mRecyclerView2.layoutManager = LinearLayoutManager(requireContext(), LinearLayoutManager.HORIZONTAL, false)
        dateAdapter = NavLiveProgramDateAdapter(requireContext())
        mRecyclerView1.adapter = dateAdapter
        dateAdapter!!.setItemClickListener { index, _, _ ->
            if (index != dateAdapter!!.selectedIndex) {
                val item = dateAdapter!!.getItem(index)
                dateAdapter!!.selectedIndex = index
                val channel = if (channelTableAdapter!!.data.size > 0) channelTableAdapter!!.data!![channelTableAdapter!!.selectedIndex] else null
                channel?.let {
                    programFragment?.updateDate(it, it.vid ?: "", "${item.date}", false, "${it.id}", it.title ?: "")
                }
            }
        }

        channelTableAdapter = NavLiveChannelTableAdapter(activity)
        mRecyclerView2.adapter = channelTableAdapter

        val channelClickListener = { index: Int, _: Boolean, adapter: BaseRecyclerAdapter<*> ->
            if (index != channelTableAdapter!!.selectedIndex) {
                channelTableAdapter!!.selectedIndex = index
                navLiveDropDownListAdapter!!.selectedIndex = index
                switchChannel(channelTableAdapter!!.getItem(index))
                //取节目单
                val item = dateAdapter!!.getItem(dateAdapter!!.selectedIndex)
                if (programFragment == null) {
                    addProgramListFragment(
                        item.date!!,
                        channelTableAdapter!!.getItem(index).vid,
                        "${channelTableAdapter!!.getItem(index).id}",
                        channelTableAdapter!!.getItem(index).title,
                        channelTableAdapter!!.getItem(index)
                    )
                }
                programFragment?.updateDate(
                    channelTableAdapter!!.getItem(index),
                    channelTableAdapter!!.getItem(index).vid,
                    "${item.date}",
                    isChangeChannel = true,
                    "${channelTableAdapter!!.getItem(index).id}",
                    channelTableAdapter!!.getItem(index).title
                )
                if (adapter is NavLiveDropDownListAdapter)
                    mRecyclerView2.scrollToPosition(index)
                closeListener(null)
            } else {
                closeListener(null)
            }
        }
        channelTableAdapter!!.setItemClickListener(channelClickListener)
        navLiveDropDownListAdapter!!.setItemClickListener(channelClickListener)
    }

    /**
     * 频道切换
     */
    private fun switchChannel(articleItem: ArticleItem) {
        //暂停视频或者音频的播放
        audioPlayer?.stop()
        videoPlayer?.pause()
        val params: MutableMap<String, String> = HashMap()
        params["client"] = DataInvokeUtil.ClientFlag
        params["navigate_id"] = "${catalog?.catid}"
        DataInvokeUtil.ziMeiTiApi.getArticleById("${articleItem.id}", params)
            .map {
                val reciver = ArticleItemReciver()
                reciver.readFromJson(it.body())
                reciver
            }
            .onErrorReturn { null }
            .subscribeOn(Schedulers.io())
            .observeOn(AndroidSchedulers.mainThread())
            .subscribe(object : Observer<ArticleItemReciver> {
                override fun onSubscribe(d: Disposable) {

                }

                override fun onNext(t: ArticleItemReciver) {
                    playVideoItem = null
                    doLiveChannelPlayHandle(t.articleItem ?: null)
                }

                override fun onError(e: Throwable) {
                    showErrorView()
                }

                override fun onComplete() {
                }
            })

    }

    private fun showErrorView() {
        videoPlayer?.prepareView?.mThumb?.setImageDrawable(null)
        videoPlayer?.onExternalError()
        ViewUtils.showSnackBar(mRootView, R.string.getlivestreamerror)
    }

    private var cdnEncrypt: String? = null

    /**
     * 视频直播
     */
    private fun playVideoLive(articleItem: ArticleItem) {
        videoPlayerContainer.removeAllViews()
        videoPlayer?.visibility = View.VISIBLE
        videoPlayerContainer.addView(videoPlayer)
        try {
            setVideoPlayerListener()
           // videoPlayer?.autoPlay = false


            val video = JSONObject(articleItem.video)
            val tsAddress = VideoAddressGet.getAddress(video)
            if (tsAddress?.length() ?: 0 > 0){
                videoPlayer?.release()
            }
            else {
                showErrorView()
                return
            }
            videoPlayer?.prepareView?.fadeOutAnimMoment = PrepareView.FADE_OUT_ANIM_WHEN_PLAYING
            videoPlayer?.setPoster(video.optString("poster", ""), ContextCompat.getDrawable(requireContext(), R.drawable.cctv7_loading_img))
            playVideoItem = XVideoItem()
            playVideoItem?.videoTitle = articleItem.title
            playVideoItem?.cdnIv = AppFactoryGlobalConfig.ServerAppConfigInfo.OtherConfig.vms_cdn_iv
            playVideoItem?.cdnKey = AppFactoryGlobalConfig.ServerAppConfigInfo.OtherConfig.vms_cdn_key


            for (i in 0 until tsAddress.length()) {
                val line = tsAddress.optJSONObject(i)
                val title = line.optString("title")
                val url = line.optString("url")
                lineMap[title] = line.optString(LiveMediaPlayBackInvoker.ReviewUrl)
                val xVideoBitRate = XVideoBitRate(title, url, video.optString("cdnConfigEncrypt"))
                playVideoItem?.bitRates?.add(xVideoBitRate)
            }
            programFragment?.isFirstPlay = true
            if (playVideoItem!!.bitRates.size > 0) {
                videoPlayer?.addVideoItem(playVideoItem!!)
                if(DeviceUtils.isCus(requireContext())){
                    videoPlayer?.setDolbySwitchViewState(true, null)
                }
            }
            isAutoPlay = true
        } catch (e: Exception) {
            e.printStackTrace()
            Log.e(TAG, "" + e.message)
            showErrorView()
        }
    }

    /**
     * Play audio live
     *
     */
    private fun playAudioLive(item: ArticleItem?) {
        videoPlayerContainer.removeAllViews()
        KillMusicUtils.stopAPS(requireActivity())
        audioPlayer = AudioLiveView(requireContext())
        audioPlayer?.setBackgroundImageUrl(radioImageUrl)
        videoPlayerContainer.addView(audioPlayer)
        if (item == null) {
            audioPlayer?.showPlayError()
            return
        }
        audioPlayer?.setLogo(item.logo)
        try {
            val `object` = JSONObject(item.audio)
            val array = `object`.getJSONArray("ANDROID")
            cdnEncrypt = `object`.getString("cdnConfigEncrypt")
            val items = ArrayList<MediaMusicItem>()
            for (i in 0 until array.length()) {
                val obj = array.getJSONObject(i)
                val audioItem = AudioItem()
                audioItem.url = obj.getString("url")
                audioItem.cdnEncrypt = cdnEncrypt
                audioItem.cdnIv = AppFactoryGlobalConfig.ServerAppConfigInfo.OtherConfig.vms_cdn_iv
                audioItem.cdnKey = AppFactoryGlobalConfig.ServerAppConfigInfo.OtherConfig.vms_cdn_key
                items.add(audioItem)
            }
            audioPlayer?.setData(items)
        } catch (e: JSONException) {
            audioPlayer?.showPlayError()
        }

        /**
         * There was no code to write, write more comments,so to keep the busy。
         *
         */
    }

    public var mCurrentLiveArticleItem: ArticleItem? = null

    /**
     * 播放选定的频道
     */
    private fun doLiveChannelPlayHandle(articleItem: ArticleItem?) {
        mCurrentLiveArticleItem = articleItem
        this.isLive = true
        if (articleItem == null) {
            showErrorView()
            return
        }
        when (articleItem.type) {
            TypeX.NEWS.LIVE_VIDEO -> {
                view_tv_page(mCurrentLiveArticleItem)
                playVideoLive(articleItem)
            }
            TypeX.NEWS.LIVE_AUDIO -> {
                playAudioLive(articleItem)
            }
        }

    }

    fun view_tv_page(articleItem: ArticleItem?) {

    }

    private fun updateDateList() {
        val date = Date()
        val dateFormat = SimpleDateFormat("yyyyMMdd", Locale.CHINA)
        val today = dateFormat.format(date)
        val find = { index: Int, item: NavDateItem ->
            if (item.date == today) {
                // item.summary = "今"
                dateAdapter!!.selectedIndex = index
            }
        }
        dateAdapter!!.data.forEachWithIndex(find)
        dateAdapter?.notifyDataSetChanged()
        mRecyclerView1.post {
            if (dateAdapter!!.data.size > 0)
                mRecyclerView1.scrollToPosition(dateAdapter!!.selectedIndex)
        }

    }

    private fun updateTableChannel() {
        channelTableAdapter?.notifyDataSetChanged()
        if (channelTableAdapter!!.data.size > 0) {
            switchChannel(channelTableAdapter!!.getItem(0))
        }
    }


    private fun addProgramListFragment(videoId: String, date: String, contentId: String, channelName: String, item: ArticleItem) {
        programFragment = NavigateLiveProgramFragment()
        val bundle = Bundle()
        bundle.putString(NavigateLiveProgramFragment.VideoID, videoId)
        bundle.putParcelable(NavigateLiveProgramFragment.Item, item)
        bundle.putString(NavigateLiveProgramFragment.Date, date)
        bundle.putString(NavigateLiveProgramFragment.ContentID, contentId)
        bundle.putString(NavigateLiveProgramFragment.ChannelName, channelName)
        programFragment!!.arguments = bundle
        childFragmentManager.beginTransaction().add(R.id.appfacProgramList, programFragment!!).commitNowAllowingStateLoss()
    }

    var fragmentIsVisiable = true
    override fun choosed() {
        super.choosed()
        if (beforeIsPlay) {
            videoPlayer?.resume()
            audioPlayer?.start()
        }
    }

    override fun onPause() {
        super.onPause()
        unChooseHandle()
    }

    override fun onResume() {
        super.onResume()
        if (hadChoosed)
            choosed()
    }


    override fun unChosoed() {
        super.unChosoed()
        unChooseHandle()
    }

    private fun unChooseHandle() {


        val isPlay: Boolean = (videoPlayer?.isPlaying == true ||
                (audioPlayer != null && audioPlayer!!.isPlaying))
        if (isPlay) {
            beforeIsPlay = true
            videoPlayer?.pause()
            audioPlayer?.pause()
        } else {
            beforeIsPlay = false
        }
    }

    override fun onDestroyView() {
        val activity = requireActivity()
        if (activity is FragmentActivityBase) {
            activity.setOnKeyCodeListener(null, true)
        }
        //  player?.iPlayerProgramLookBack = null
        dateAdapter?.setItemClickListener(null)
        channelTableAdapter?.setItemClickListener(null)
        navLiveDropDownListAdapter?.setItemClickListener(null)
        closeChannelList?.setOnClickListener(null)
        quit_tv_playback()
        quit_tv_live(mCurrentLiveArticleItem)
        super.onDestroyView()
    }

    override fun onDestroy() {
        intervalDisposable?.dispose()
        playBillDisposable?.dispose()

        videoPlayer?.let {
            it.connectivityEngine.unregisterNetworkChangeListener()
            it.adImageView?.cancelCountDown()
            if (it.cdnUrl != null) {
                it.preloadManager.removePreloadTask(it.cdnUrl)
            }
            it.vRLibrary?.onDestroy()
            if (context is LifecycleOwner) {
                (context as LifecycleOwner).lifecycle.removeObserver(it)
            }
            it.release()
            if (EventBus.getDefault().isRegistered(it)) {
                EventBus.getDefault().unregister(it)
            }
        }

        audioPlayer?.stop()

        if (programFragment != null) {
            childFragmentManager.beginTransaction().remove(programFragment!!).commitNowAllowingStateLoss()
        }
        updateHandle.removeMessages(2)
        super.onDestroy()
    }


    override fun onHiddenChanged(hidden: Boolean) {
        super.onHiddenChanged(hidden)
        if (hidden) {
            fragmentIsVisiable = false
            unChooseHandle()
        } else fragmentIsVisiable = true
    }


    private var radioImageUrl: String? = null


    private val updateHandle: Handler = object : Handler(Looper.getMainLooper()) {
        override fun handleMessage(msg: Message) {
            super.handleMessage(msg)
            if (msg.what == 1) {
                if (programList != null && programList!!.size > 0) {
                    if (msg.arg1 < programList!!.size - 1) {
                        val item2: ProgramListItem = programList!!.get(msg.arg1 + 1)
                        handleReplay(item2)
                    } else {
                        this.removeMessages(1)
                    }
                }
            }
        }
    }

    var index = 0
    var programListItem: ProgramListItem? = null
    internal fun handleReplay(item: ProgramListItem) {
        quit_tv_playback()
        quit_tv_live(mCurrentLiveArticleItem)
        this.programListItem = item
        isLive = false
        if (programFragment != null) programFragment?.freshAdapter(item)
        try {
            updateHandle.removeMessages(1)
            if (programList != null) {
                for (i in programList!!.indices) {
                    if (programList!![i].id == item.id) {
                        index = i
                        break
                    }
                }
            }
            updateHandle.postDelayed({
                val now = System.currentTimeMillis()
                val startTime = DateParse.parseDate(item.starttime, null)
                val endDate = DateParse.parseDate(item.endtime, null)
                val delay = if (now > endDate.time) {
                    endDate.time - startTime.time
                } else {
                    if (now > startTime.time) {
                        endDate.time - now
                    } else {
                        endDate.time - startTime.time
                    }
                }

                if (delay > 0L) {
                    val msg = Message()
                    msg.what = 1
                    msg.arg1 = index
                    updateHandle.sendMessageDelayed(msg, delay)
                }
            }, 0)
//            player?.setErrorViewVisible(View.GONE)
//            player?.stop()
            videoPlayer?.release()
            val state = if (item.playerStart > 0L) { //startLong！=0 说明是来自进度条节目单
                if (System.currentTimeMillis() > item.playerStart) {
                    ProgramListItem.GuideItemState.REPLAY
                } else {
                    ProgramListItem.GuideItemState.LIVE
                }
            } else if (item.playerStart == -1L) {
                ProgramListItem.GuideItemState.LIVE
            } else {
                ProgramListItem.getItemState(item)
            }
            if (item.isPlaying == 0) {
//                player?.setLiveIvPoser(item.placeholder, 0)
//                if (ProgramListItem.GuideItemState.REPLAY == state) {
//                    if (item.playerStart == 0L) {  //startLong==0 说明不是来自进度条节目单
//                        player?.setProgramComponentLookBack(item.starttime)
//                    }
//                }
            } else {
                videoPlayer?.autoPlay = true
//                player?.setLiveIvPoser(item.placeholder, 8)

                val keySet = lineMap.entries
                val iterator = keySet.iterator()

                if (ProgramListItem.GuideItemState.REPLAY == state) {
                    videoPlayer?.prepareView?.fadeOutAnimMoment = PrepareView.FADE_OUT_ANIM_OFF
                    while (iterator.hasNext()) {
                        val entry = iterator.next()
//
                        val url = entry.value

                        val startDate: Date
                        var endDate: Date? = null
                        if (item.playerStart != 0L) {
                            startDate = Date(item.playerStart)
                        } else {
                            startDate = DateParse.parseDate(item.starttime, null)
                            endDate = DateParse.parseDate(item.endtime, null)
                        }

                        getLookBack(
                            url,
                            URLAuth.EncrptMode(
                                cdnEncrypt,
                                AppFactoryGlobalConfig.ServerAppConfigInfo.OtherConfig.vms_cdn_key,
                                AppFactoryGlobalConfig.ServerAppConfigInfo.OtherConfig.vms_cdn_iv
                            )?.code,
                            startDate.time,
                            endDate?.time ?: 0L
                        )
//                        if (item.playerStart == 0L) {  //startLong==0 说明不是来自进度条节目单
//                            player?.setProgramComponentLookBack(item.starttime)
//                        }
                        break
                    }
                } else if (ProgramListItem.GuideItemState.LIVE == state) {
                    videoPlayer?.prepareView?.fadeOutAnimMoment = PrepareView.FADE_OUT_ANIM_WHEN_PLAYING
                    //   player?.mediaObjs?.clear()
                    videoPlayer?.autoPlay = true
                    videoPlayer?.isLiveReplay = false

                    playVideoItem?.let {
                        if (playVideoItem!!.bitRates.size > 0) {
                            videoPlayer?.addVideoItem(playVideoItem!!)
                            if(DeviceUtils.isCus(requireContext())){
                                 videoPlayer?.setDolbySwitchViewState(true, null)
                            }
                            videoPlayer?.bottomControl?.setPlayingBack(false)
                        }
                    }


//                    if (item.playerStart == 0L) {  //startLong==0 说明不是来自进度条节目单
//                        player?.setProgramComponentLookBack(null)
//                    }
//                    player?.onLookBackResult(true)
                }
                setVideoPlayerListener()
            }
        } catch (e: Exception) {
            e.printStackTrace()
        }
    }

    var isLive = false

    var isStartPlayLive = false
    var mTyReportStartPlayTime: Long = 0
    var mTyReportEndPlayTime: Long = 0

    var isStartPlaybackLive = false
    var mTyReportStartPlaybackTime: Long = 0
    var mTyReportEndPlaybackTime: Long = 0
    fun watch_tv_video(articleItem: ArticleItem?) {
        if (isLive) {
            quit_tv_live(mCurrentLiveArticleItem)
            quit_tv_playback()
            if (articleItem != null) {
                if (!isStartPlayLive) {
                    mTyReportStartPlayTime = System.currentTimeMillis()
                    mTyReportEndPlayTime = mTyReportStartPlayTime
                    isStartPlayLive = true
                }
            }
        }
    }

    fun quit_tv_live(articleItem: ArticleItem?) {
        if (isLive) {
            if (articleItem != null) {
                if (isStartPlayLive) {
                    if (mTyReportStartPlayTime > 0) {
                        mTyReportEndPlayTime = System.currentTimeMillis()
                    }
                    isStartPlayLive = false
                }
            }
        }
    }

    fun watch_tv_playback() {
        quit_tv_live(mCurrentLiveArticleItem)
        quit_tv_playback()


        if (!isLive) {
            if (mCurrentLiveArticleItem != null) {
                if (!isStartPlaybackLive) {
                    mTyReportStartPlaybackTime = System.currentTimeMillis()
                    mTyReportEndPlaybackTime = mTyReportStartPlaybackTime
                    isStartPlaybackLive = true
                }
            }
        }
    }

    fun quit_tv_playback() {
        if (!isLive) {
            if (mCurrentLiveArticleItem != null) {
                if (isStartPlaybackLive) {
                    if (mTyReportStartPlaybackTime > 0) {
                        mTyReportEndPlaybackTime = System.currentTimeMillis()
                    }
                    isStartPlaybackLive = false
                }
            }
        }
    }

    private val playerListener = object : BaseVideoView.OnStateChangeListener {
        override fun onPlayerStateChanged(playerState: Int) {
            if (playerState == VideoView.PLAYER_FULL_SCREEN) {
                enterFullScreen()
            } else {
                exitFullScreen()
            }
            programFragment?.needScrollToPosition = true
            programFragment?.scrollToPosition()
        }

        override fun onPlayStateChanged(playState: Int) {
            when (playState) {
                VideoView.STATE_PREPARED -> {
                    if (programFragment != null) {
                        programFragment?.setPlay()
                    }
                    if (fragmentIsVisiable) {
                        videoPlayer?.resume()
                    } else {
                        videoPlayer?.pause()
                    }
                    if (isLive) {
                        watch_tv_video(mCurrentLiveArticleItem)
                    } else {
                        watch_tv_playback()
                    }
                }
                VideoView.STATE_ERROR -> {

                }
            }
        }
    }


    private fun enterFullScreen() {
        videoPlayer?.let {
            val parent = it.parent as ViewGroup
            parent.removeView(it)
            val view = requireActivity().findViewById<ViewGroup>(android.R.id.content)
            view.addView(it)
        }
    }


    private fun exitFullScreen() {
        videoPlayer?.let {
            val parent = it.parent as ViewGroup
            parent.removeView(it)
            videoPlayerContainer.addView(it)
        }
    }

    private fun setVideoPlayerListener() {

        videoPlayer?.addOnStateChangeListener(playerListener)
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        this.navPaddingTopMatch()
        val activity = requireActivity()
        if (activity is FragmentActivityBase) {
            activity.setOnKeyCodeListener(FragmentActivityBase.OnKeyListener { keyCode, event ->
                return@OnKeyListener onKeyDown(keyCode, event)
            }, true)
        }
    }

    protected var mExitTime: Long = 0


    fun exitApp() {
        if (System.currentTimeMillis() - mExitTime > 2000) {
            com.utils.ToastUtil.showToastCenter(requireContext(), R.string.exit_app, Toast.LENGTH_SHORT)
        } else {
            requireActivity().finish()
        }
        mExitTime = System.currentTimeMillis()
    }

    private var programList: MutableList<ProgramListItem>? = null
    fun setPrograms(programList: MutableList<ProgramListItem>?) {
        this.programList = programList
        val programs: MutableList<IProgram> = ArrayList()
        programList?.forEach {
            programs.add(ProgramMod(it.name, it.starttime))
        }
        //  player?.setProgramList(programs)
    }

//    override fun onLookBackTimeStampChanged(time: Long) {
//     //   player?.loadingViewControl?.hidePoster()
//
//        var item: ProgramListItem? = null
//        programList?.let {
//            for (i in it.indices) {
//                if (time == -1L && ProgramListItem.getItemState(it[i]) == ProgramListItem.GuideItemState.LIVE) {
//                    item = it[i]
//                    break
//                } else if (it[i].startLong <= time && it[i].endLong >= time) {
//                    item = it[i]
//                    break
//                }
//            }
//        }
//        item?.let {
//            it.playerStart = time
//            handleReplay(it)
//        }
//        if (time == -1L) {
//            item?.startLong?.let {
//                setPlayingStartTime(it)
//            }
//        } else
//            setPlayingStartTime(time)
//    }

    private fun setPlayingStartTime(time: Long) {
        val simpleDateFormat = SimpleDateFormat("yyyyMMdd", Locale.CHINA)
        val formatDate = simpleDateFormat.format(time)
        dateAdapter?.data?.let { items ->
            for (i in 0 until items.size) {
                if (items[i].date == formatDate) {
                    dateAdapter?.selectedIndex = i
                    mRecyclerView1.scrollToPosition(i)
                    dateAdapter?.notifyDataSetChanged()
                    val channel = if (channelTableAdapter!!.data.size > 0) channelTableAdapter!!.data!![channelTableAdapter!!.selectedIndex] else null
                    if (channel != null)
                        programFragment?.updateDate(channel, channel?.vid ?: "", formatDate, false, "${channel?.id}", channel?.title)
                    break
                }
            }
        }
    }
}